package com.boot.main.service.impl;

import com.boot.main.entity.ScomCity;
import com.boot.main.mapper.ScomCityMapper;
import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.ICityService;
import com.boot.main.utils.IsNotEmptyUtil;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CityService implements ICityService {
    @Resource
    private ScomCityMapper cityMapper;

    @Override
    public ResponseData getCity(){
        List<ScomCity> items = cityMapper.getCity();
        List<ScomCity> root = getRoot(items);
        List<ScomCity> city = getCityTree(items, root);
        return ResponseDataUtil.success("获取城市列表成功", root);
    }

    public List<ScomCity> getRoot(List<ScomCity> items){
        List<ScomCity> root = new ArrayList();
        for(ScomCity item : items){
            if(item.getPid() == 1){
                root.add(item);
            }
        }
        return root;
    }

    public List<ScomCity> getCityTree(List<ScomCity> items, List<ScomCity> root){
        for(ScomCity base:root){
            base.setChildren(new ArrayList());
            for(ScomCity item:items){
               if(base.getId() == item.getPid()){
                   base.getChildren().add(item);
                   getCityTree(items, base.getChildren());
               }
            }
            if(base.getChildren().size() == 0){
                base.setChildren(null);
            }
        }
        return root;
    }
}
